#!/usr/bin/env python3
"""
Simple build script for PDF Splitter Windows executable.
"""

import os
import sys
import shutil
import subprocess
from pathlib import Path

def run_command(cmd, cwd=None):
    """Run command and return result."""
    print(f"Running: {cmd}")
    result = subprocess.run(cmd, cwd=cwd, shell=True, capture_output=False)
    if result.returncode != 0:
        print(f"Command failed with exit code: {result.returncode}")
        return False
    return True

def main():
    """Simple build process."""
    print("=" * 60)
    print("PDF Splitter Simple Build Script")
    print("=" * 60)

    # Ensure we're in the right directory
    os.chdir(Path(__file__).parent)

    # Clean previous builds
    print("\n1. Cleaning previous builds...")
    for dir_name in ["build", "dist"]:
        if Path(dir_name).exists():
            shutil.rmtree(dir_name)
            print(f"   Removed {dir_name}")

    # Install PyInstaller using UV (if available)
    print("\n2. Installing PyInstaller...")
    if run_command("uv add --dev pyinstaller"):
        print("   ✓ PyInstaller installed via UV")
    else:
        print("   ✗ Failed to install PyInstaller via UV")
        # Try direct PyInstaller command
        if not run_command("pyinstaller --version"):
            print("   PyInstaller not found. Please install it:")
            print("   pip install pyinstaller")
            sys.exit(1)

    # Build the executable
    print("\n3. Building executable...")

    # Simple one-file build
    cmd = """pyinstaller ^
        --windowed ^
        --onefile ^
        --name PDF_Splitter ^
        --add-data "src/pdf_splitter/i18n;pdf_splitter/i18n" ^
        --hidden-import PyQt6.QtCore ^
        --hidden-import PyQt6.QtGui ^
        --hidden-import PyQt6.QtWidgets ^
        --hidden-import fitz ^
        --hidden-import pdf_splitter.i18n ^
        src/pdf_splitter/main.py"""

    if run_command(cmd):
        print("   ✓ Build successful!")
    else:
        print("   ✗ Build failed!")
        sys.exit(1)

    # Check results
    exe_path = Path("dist/PDF_Splitter.exe")
    if exe_path.exists():
        size_mb = exe_path.stat().st_size / 1024 / 1024
        print(f"\n4. Build completed!")
        print(f"   Executable: {exe_path.absolute()}")
        print(f"   Size: {size_mb:.1f} MB")
        print("\nYou can now run the executable:")
        print(f"   {exe_path}")
    else:
        print("\n✗ Executable not found!")
        sys.exit(1)

if __name__ == "__main__":
    main()